package net.zoneland.knowledge.controller;

import javax.servlet.http.HttpServletRequest;

import net.zoneland.knowledge.controller.bean.UomUserOrgQueryVo;
import net.zoneland.knowledge.model.PartyOrgVoForSelect;
import net.zoneland.knowledge.service.PartyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import net.zoneland.knowledge.constant.Constants;
import net.zoneland.knowledge.model.LoginUserPojo;
import net.zoneland.knowledge.utils.LoginUtils;

import java.util.List;
import java.util.Optional;

/**
 * baseController.
 * 定义通用方法
 */
public abstract class AbstractBaseController extends BaseController {

    /**
     * 党员/党组织业务接口.
     */
    @Autowired
    private PartyService partyService;

    /**
     * 获取当前登录用户.
     * @param request 请求对象
     * @return 当前登录用户
     */
    protected LoginUserPojo getAndCheckCurrentUser(final HttpServletRequest request) {
        LoginUserPojo user = LoginUtils.getCurrentUserByToken(request.getHeader(Constants.TOKEN_NAME));
        Assert.notNull(user, "用户未登录或登录信息不存在");
        return user;
    }

    /**
     * 查询党组织.
     * @param level
     * @param orgUuid 部门Id.
     * @return
     * @throws Exception
     */
    protected List<PartyOrgVoForSelect> queryOrgTree(final int level, final String orgUuid) {
        final UomUserOrgQueryVo orgQueryVo = new UomUserOrgQueryVo();
        orgQueryVo.setLevel(level);
        orgQueryVo.setParentOrgUuid(orgUuid);
        return partyService.searchOrgByConditionForTree(orgQueryVo);
    }

    /**
     * 获取当前登录用户.
     * @param request 请求对象
     * @param token 用户token
     * @return 当前登录用户
     */
    protected LoginUserPojo getAndCheckCurrentUser(final HttpServletRequest request, final String token) {
        final String userToken = Optional.ofNullable(request.getHeader(Constants.TOKEN_NAME)).orElse(token);
        final LoginUserPojo user = LoginUtils.getCurrentUserByToken(userToken);
        Assert.notNull(user, "用户未登录或登录信息不存在");
        return user;
    }

}
